﻿using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Edu.Web.Security;
using ESoft.Core.Initialize;
using ESoft.Core.Logging;
using ESoft.Core.Logging.Log4Net;

namespace Edu.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            DatabaseInitialize();
            LoggingInitialize();
           
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            AutoFacBootStrapper.CoreAutoFacInit();
        }

        // 获取依赖程序集中的实体集合
        private static void DatabaseInitialize()
        {
            var assmblyArr = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
            DatabaseInitializer.AddMapperAssembly(assmblyArr);
            DatabaseInitializer.Initialize();
        }

        // Log4net日志配制
        private static void LoggingInitialize()
        {
            Log4NetLoggerAdapter adapter = new Log4NetLoggerAdapter();
            LogManager.AddLoggerAdapter(adapter);
        }

        // 拦截每次请求在设置User对象方便使用
        protected void Application_PostAuthenticateRequest(object sender, System.EventArgs e)
        {
            var formsIdentity = HttpContext.Current.User.Identity as FormsIdentity;
            if (formsIdentity != null && formsIdentity.IsAuthenticated && formsIdentity.AuthenticationType == "Forms")
            {
                HttpContext.Current.User =
                    FormsAuthentication<User>.TryParsePrincipal(HttpContext.Current.Request);
            }
        }
    }
}
